<template>
  <div ref="imageWrapper">
    <div class="modelTitle"><h2>基建类绩效考核模型</h2></div>
    <a-card title="查询条件" class="search">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form-model
          ref="ruleForm"
          :model="queryParam"
          :rules="rules"
          layout="inline"
          @keyup.enter.native="searchQuery"
        >
          <a-row :gutter="24">
            <a-col :md="6" :sm="8">
              <a-form-model-item label="审计单位" prop="orgName">
                <a-input v-model="queryParam.orgName" readOnly placeholder="请选择" @click.native="openOrganModel" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="6">
              <a-form-model-item label="审计时间" prop="arrayTime">
                <a-range-picker
                  :mode="['year', 'year']"
                  v-model="queryParam.arrayTime"
                  format="yyyy"
                  value-format="yyyy"
                  @change="handleDatechange"
                  @panelChange="handlePanelChange"
                />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="6">
              <span style="float: right" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" icon="search" class="yellow_search_btn">查询</a-button>
                <a-button @click="searchReset" icon="reload" class="clear_btn">清除条件</a-button>
                <a-button
                  type="danger"
                  :loading="ydLoading"
                  icon="arrow-right"
                  style="margin-left: 18px"
                  @click="handleToYD(false)"
                  >转疑点</a-button
                >
              </span>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <a-card style="margin-top: 20px">
      <a-table
        bordered
        :columns="columns"
        :data-source="dataSource"
        rowKey="line_num"
        :pagination="false"
        :loading="loading"
        :scroll="{ x: aotuScrollX }"
        :row-selection="rowSelection"
      >
        <template slot="title">
          单位：万元
        </template>
        <div slot="customTitle" style="position: relative">
          <div style="position: absolute; top: 14px; left: -55px">年份</div>
          <div style="position: absolute; top: -11px; left: 46px; width: 30px">指标</div>
          <div
            style="
              content: '';
              position: absolute;
              width: 1px;
              height: 167px;
              top: -74px;
              left: 0px;
              background-color: rgb(200 207 211);
              display: block;
              transform: rotate(-71deg);
              box-sizing: border-box;
            "
          ></div>
        </div>
      </a-table>
      <a-card style="margin-top: 20px" v-if="isEmpty">
        <a-empty />
      </a-card>
    </a-card>

    <AuditDepart ref="AuditDepart" @selectedRow="updateQueryParam" />
    <YDModel ref="YDModel" :router-data="$route.path" />
  </div>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction, postAction } from '@/api/manage'
import AuditDepart from '@/views/sj/sjmxgl/cwzb/components/AuditDepart'
import { beforeyearYMD, currentYMD } from '@/mixins/commontime.js'
import columns from './columns'
import YDModel from './YDModel'
import { base64toImg } from '@/mixins/base64toImg'
import html2canvas from 'html2canvas'
import moment from 'moment'
export default {
  mixins: [JeecgListMixin, base64toImg],
  components: { AuditDepart, YDModel },
  watch: {
    $route: {
      handler: function(to) {
        if (Object.keys(to.query).length) {
          this.disableMixinCreated = true
          console.log(to.query)
          this.selectedRowKeys = to.query.selectedRowKeys.split(',').map(item => parseInt(item)) || []
          to.query.selectedRowKeys && delete to.query.selectedRowKeys
          this.queryParam = Object.assign(this.queryParam, to.query)
          this.queryParam.arrayTime = to.query.arrayTime.split(',')
          this.$nextTick(() => {
            this.searchQuery()
          })
        }
      },
      immediate: true
    }
  },
  data() {
    return {
      queryParam: {
        orgId: '',
        orgName: '',
        endYear: '',
        startYear: '',
        arrayTime: ['', '']
      },
      superParam: {
        id: '234sgdf54dfb4341234123fassd3fdsdf',
        modelId: '234sgdf54dfb4341234123fassd3fdsdf',
        extraFlag: true
      },
      url: {
        list: '/sjmx/queryJJLJXKH',
        // 查询模型转疑点信息(多选)
        TurnSuspects: '/sjmx/queryModelMsgMulti'
      },
      columns: columns(),
      disableMixinCreated: true,
      dataSource: [],
      rules: {
        orgName: [{ required: true, message: '请选择审计单位' }],
        arrayTime: [{ required: true, message: '请选择审计时间' }]
      },
      isEmpty: false,
      selectedRowKeys: [],
      tempPlace: []
    }
  },
  computed: {
    aotuScrollX() {
      return (this.columns.length - 10) * 130 + 1000
    },
    // 行选择
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          console.log(selectedRowKeys)
          this.selectedRowKeys = [...selectedRowKeys]
          this.selectedRows = [...selectedRows]
        }
      }
    }
  },
  methods: {
    searchReset() {
      this.queryParam = this.$options.data().queryParam
      this.selectedRowKeys = []
      this.dataSource = []
      this.columns = columns()
    },
    updateQueryParam(checkRow) {
      this.queryParam.orgName = checkRow.departName
      this.queryParam.orgId = checkRow.id
    },
    openOrganModel() {
      this.$refs.AuditDepart.show()
    },
    handleDatechange(dates) {
      this.queryParam.startYear = dates[0]
      this.queryParam.endYear = dates[1]
    },
    handlePanelChange(value, mode) {
      this.queryParam.startYear = moment(value[0]).format('YYYY')
      this.queryParam.endYear = moment(value[1]).format('YYYY')
      this.queryParam.arrayTime = [moment(value[0]).format('YYYY'), moment(value[1]).format('YYYY')]
      console.log(this.queryParam.startYear, this.queryParam.endYear)
    },
    handleOk(checkRow, keyStr) {
      this.queryParam.accName = checkRow[0].title
      this.queryParam.unitId = keyStr
      console.log(checkRow, keyStr)
    },
    handlerCheckDeatil(text, record) {
      // 点击跳转
      if (Number(text) === 0) {
        this.$message.warning('无当前数据')
      } else {
        let key = Object.keys(record).find(item => {
          if (record[item] == text) return item
        })
        let year = `${key.substring(0, 4)}-01-01`
        let params = Object.assign({}, this.queryParam)
        if (record.line_num == 9) {
          params.direction = -1
        } else if (record.line_num == 10) {
          params.direction = 1
        }
        this.$refs.CheckDetail.edit(params, record, year)
      }
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() // 查询条件
      this.loading = true
      this.columns = columns(this)
      for (let index = this.queryParam.startYear; index <= this.queryParam.endYear; index++) {
        // this.columns.splice(this.columns.length - 1, 0, {})
        this.columns.push({
          title: `${index}年`,
          children: [
            {
              title: '预算值',
              dataIndex: `${index}_budget`
            },
            {
              title: '实际值',
              dataIndex: `${index}_real`
            }
          ]
        })
      }

      //   this.dataSource = []
      getAction(this.url.list, params).then(res => {
        if (res.success) {
          this.dataSource = this.rowSpan2(res.result.records || res.result, 'type')
          if (res.result.total) {
            this.ipagination.total = res.result.total
          } else {
            this.ipagination.total = 0
          }
        } else {
          this.$message.error(res.message)
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    rowSpan2(data, field) {
      let count = 0 //重复项的第一项
      let indexCount = 1 //下一项
      while (indexCount < data.length) {
        var item = data.slice(count, count + 1)[0] //获取没有比较的第一个对象
        if (!item[`${field}rowSpan`]) {
          item[`${field}rowSpan`] = 1 //初始化为1
        }
        if (item[field] === data[indexCount][field]) {
          //第一个对象与后面的对象相比，有相同项就累加，并且后面相同项设置为0
          item[`${field}rowSpan`]++
          data[indexCount][`${field}rowSpan`] = 0
        } else {
          count = indexCount
        }
        indexCount++
      }
      return data
    },
    handleToYD(record) {
      if (this.dataSource.length) {
        const { startYear = '', endYear = '' } = this.queryParam
        let param = Object.assign({}, this.queryParam, {
          selectedRowKeys: this.selectedRowKeys.join(',')
        })
        let ydnr = undefined
        let gzzd = undefined
        // if (record) {
        //   ydnr = `【科目代码：${record.subjectCode}】【科目名称：${record.subjectName}】`
        // }
        let time = `【${startYear}～${endYear}】【基建类绩效考核模型】`
        this.addYd(param, ydnr, time, gzzd)

        let ydList = JSON.stringify(this.selectedRows)
        postAction(this.url.TurnSuspects, Object.assign({}, this.queryParam, this.superParam, { ydList: ydList })).then(
          res => {
            if (res.success) {
              if (res.result.length) {
                ydnr = res.result[0].ydms ? res.result[0].ydms : ydnr
                gzzd = res.result[0].gzzd ? res.result[0].gzzd : gzzd
              }
              this.addYdMulti(param, ydnr, time, gzzd)
            } else {
              this.$message.error(res.message)
            }
            if (res.code === 510) {
              this.$message.warning(res.message)
            }
          }
        )
      } else {
        this.$message.error('空数据不能新建疑点')
      }
    },
    addYd(record, ydnr, time, gzzd) {
      this.ydLoading = true
      html2canvas(this.$refs.imageWrapper).then(canvas => {
        let dataURL = canvas.toDataURL('image/png')
        console.log('父组件调用完了')
        this.$refs.YDModel.show(record, dataURL, ydnr, time, gzzd)
        this.ydLoading = false
      })
    }
  }
}
</script>
<style lang="less">
.bgc_tooltip {
  .ant-tooltip-inner {
    // 这里是框框
    border-radius: 20px;
    color: #333;
    width: 400px;
    padding: 10px 15px;
    background-color: rgba(255, 255, 255, 0.8) !important;
  }

  .ant-tooltip-arrow::before {
    // 这里是小三角形
    background-color: #fff !important;
  }
}
</style>
<style lang="less" scoped>
@import '~@assets/less/tableTheme.less';

.ant-table-fixed-left .ant-table-thead > tr > th:last-child {
  border-top-right-radius: 0;
  background-color: red;
  padding: 0;
}
.antableClass {
  /deep/.ant-table-thead tr th {
    text-align: center !important;
  }
}
.modelTitle {
  display: flex;
  justify-content: center;
  align-items: center;
  h2 {
    font-weight: 600;
  }
}
</style>
